<?php
/**
 * des:AliDingDingUtil.php
 * User: liangbo
 * Date: 2018/3/20
 * Time: 下午10:59
 * 钉钉企业接口
 */

namespace api\util;

use api\models\CheckinRecordVo;
use api\models\DepartList;
use api\models\ProcessInstanceTopVo;
use api\models\UserList;
use yii;

class AliDingDingUtil
{
    const ACCESS_TOKEN_URL = 'https://oapi.dingtalk.com/gettoken?corpid={{corpid}}&corpsecret={{corpsecret}}';
    const DEPART_MENT_URL = 'https://oapi.dingtalk.com/department/list?access_token={{access_token}}';
    const MEMBER_LIST_URL = 'https://oapi.dingtalk.com/user/list?access_token={{access_token}}&department_id={{department_id}}';

    /**
     * 获取考情签到记录
     * @param $useridlist
     * @param $cursor
     * @param $starttime
     * @param $endtime
     * @param $access_token
     * @param $size
     * @return mixed|\ResultSet|\SimpleXMLElement
     */
    public function getrecord($useridlist, $cursor, $starttime, $endtime, $access_token, $size)
    {
        require_once "AliSdk/TopSdk.php";
        $c = new \DingTalkClient;
        $c->format="json";
        $req = new \SmartworkCheckinRecordGetRequest;
        $req->setUseridList($useridlist);
        $req->setStartTime($starttime);
        $req->setEndTime($endtime);
        $req->setCursor($cursor);
        $req->setSize($size);
        $resp = $c->execute($req, $access_token);
        return $resp;
    }

    /**
     * 获取审批列表
     * @param $process_code //审批实例
     * @param $starttime //开始时间
     * @param $endtime //结束时间
     * @param $size //长度
     * @param $cursor //分页
     * @param $useridlist //管理id
     * @param $access_token //授权
     * @return mixed|\ResultSet|\SimpleXMLElement
     */
    public function getSplist($process_code, $starttime, $endtime, $size, $cursor, $useridlist, $access_token)
    {
        require_once "AliSdk/TopSdk.php";
        $c = new \DingTalkClient;
        $req = new \SmartworkBpmsProcessinstanceListRequest;
        $req->setProcessCode($process_code);
        $req->setStartTime($starttime);
        $req->setEndTime($endtime);
        $req->setSize($size);
        $req->setCursor($cursor);
        $req->setUseridList($useridlist);
        $resp = $c->execute($req, $access_token);
        return $resp;
    }

    /**
     * 获得access_token
     * @return mixed|string
     */
    public function getAccess_token()
    {
        $access_token = Yii::$app->cache->get("o_access_token");
        if (empty($access_token)) {
            $access_token = "";
            $corpid = yii::$app->params["CorpSecret"]["CorpId"];
            $secrect = yii::$app->params["CorpSecret"]["CorpSecret"];
            $url = self::ACCESS_TOKEN_URL;
            $url = str_replace("{{corpid}}", $corpid, $url);
            $url = str_replace("{{corpsecret}}", $secrect, $url);
            $result = \GuzzleHttp\json_decode($this->curl_get_https($url));
            if (isset($result->errcode) && $result->errcode == 0) {
                Yii::$app->cache->set("o_access_token", $result->access_token, $result->expires_in);
                $access_token = $result->access_token;
            }
        }
        return $access_token;
    }

    public function curl_get_https($url)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //关闭URL请求
        curl_close($curl);
        return $tmpInfo;    //返回json对象
    }

    /**
     * 获取部门信息
     * @return mixed
     */
    public function getDepart()
    {
        $access_token = $this->getAccess_token();
        $url = self::DEPART_MENT_URL;
        $url = str_replace("{{access_token}}", $access_token, $url);
        $res = \GuzzleHttp\json_decode($this->curl_get_https($url . "&fetch_child=true"));
        if (isset($res->errcode) && $res->errcode == 0) {
            foreach ($res->department as $k => $v) {
                $Dep = DepartList::find()->where(array("depart_id" => $v->id))->one();
                if (empty($Dep)) {
                    Yii::$app->db->createCommand()->insert('depart_list', [
                        'name' => $v->name,
                        'createDeptGroup' => $v->createDeptGroup,
                        'depart_id' => $v->id,
                        'autoAddUser' => $v->autoAddUser,
                        'delete' => false,
                    ])->execute();
                } else {
                    Yii::$app->db->createCommand()->update('depart_list', [
                        'name' => $v->name,
                        'createDeptGroup' => $v->createDeptGroup,
                        'autoAddUser' => $v->autoAddUser,
                        'delete' => false,
                    ], array("depart_id" => $v->id))->execute();
                }

            }
        }
        return $res;
    }

    /**
     *获取所有成员的信息
     */
    public function getAllMember()
    {
        $res = $this->getDepart();
        if (isset($res->errcode) && $res->errcode == 0) {
            foreach ($res->department as $k => $v) {
                $url = self::MEMBER_LIST_URL;
                $url = str_replace("{{access_token}}", $this->getAccess_token(), $url);
                $url = str_replace("{{department_id}}", $v->id, $url);
                $resp = \GuzzleHttp\json_decode($this->curl_get_https($url));
                foreach ($resp->userlist as $k =>$v) {
                    $Dep = UserList::find()->where(array("openId" => $v->openId))->one();
                    if (empty($Dep)) {
                        Yii::$app->db->createCommand()->insert('user_list', [
                            'unionid' => $v->unionid,
                            'openId' => $v->openId,
                            'userid' => $v->userid,
                            'email' => $v->email,
                            'department' => \GuzzleHttp\json_encode($v->department),
                            'isBoss' => $v->isBoss,
                            'order' => $v->order,
                            'dingId' => $v->dingId,
                            'isLeader' => $v->isLeader,
                            'mobile' => $v->mobile,
                            'active' => $v->active,
                            'isAdmin' => $v->isAdmin,
                            'avatar' => $v->avatar,
                            'isHide' => $v->isHide,
                            'name' => $v->name,
                        ])->execute();
                    } else {
                        Yii::$app->db->createCommand()->update('user_list', [
                            'unionid' => $v->unionid,
                            'userid' => $v->userid,
                            'email' => $v->email,
                            'department' => \GuzzleHttp\json_encode($v->department),
                            'isBoss' => $v->isBoss,
                            'order' => $v->order,
                            'dingId' => $v->dingId,
                            'isLeader' => $v->isLeader,
                            'mobile' => $v->mobile,
                            'active' => $v->active,
                            'isAdmin' => $v->isAdmin,
                            'avatar' => $v->avatar,
                            'isHide' => $v->isHide,
                            'name' => $v->name,
                        ], array("openId" => $v->openId))->execute();
                    }
                }
            }
        }
        return UserList::find()->all();

    }

    /**
     *获得签到记录
     */
    public function getrecordlist()
    {
        $userlist=UserList::find()->select("userid")->all();
        $str=array();
        foreach ($userlist as $k=>$v)
        {
            $str[$k]=$v["userid"];
        }
        $useridlist=implode(",",$str);
        if(!empty($useridlist))
        {
            $starttime=(time()-60*60*24*2)*1000;
            $endtime=time()*1000;
            $res=$this->getrecord($useridlist,"0","{$starttime}","{$endtime}",$this->getAccess_token(),"100");
            if(isset($res->result->success)&&$res->result->success)
            {

                if(isset($res->result->result->page_list->checkin_record_vo))
                {
                    $vv=$res->result->result->page_list->checkin_record_vo;
                    foreach ($vv as $k=>$v)
                    {
                        $item=CheckinRecordVo::find()->where(array("checkin_time"=>trim($v->checkin_time),"userid"=>trim($v->userid)))->all();
                        if(empty($item))
                        {
                            Yii::$app->db->createCommand()->insert('checkin_record_vo', [
                                'checkin_time' => trim($v->checkin_time),
                                'image_list' => \GuzzleHttp\json_encode($v->image_list),
                                'detail_place' => isset($v->detail_place)?$v->detail_place:"",
                                'remark' => isset($v->remark)?$v->remark:"",
                                'userid' => trim($v->userid),
                                'place' => isset($v->place)?$v->place:"",
                                'longitude' => isset($v->longitude)?$v->longitude:"",
                                'visit_user' => isset($v->visit_user)?$v->visit_user:"",
                                'latitude' => isset($v->latitude)?$v->latitude:"",
                            ])->execute();
                        }
                    }
                }

                if(isset($res->result->result->next_cursor))
                {
                    $this->dogetrecordlist($useridlist,$res->result->result->next_cursor,$starttime,$endtime);
                }
            }
        }
        return CheckinRecordVo::find()->all();
    }

    private function dogetrecordlist($useridlist,$cursor,$starttime,$endtime)
    {
        $res=$this->getrecord($useridlist,$cursor,"{$starttime}","{$endtime}",$this->getAccess_token(),"100");
        if(isset($res->result->success)&&$res->result->success)
        {
            if(isset($res->result->result->page_list->checkin_record_vo))
            {
                $vv=$res->result->result->page_list->checkin_record_vo;
                foreach ($vv as $k=>$v)
                {
                    $item=CheckinRecordVo::find()->where(array("checkin_time"=>trim($v->checkin_time),"userid"=>trim($v->userid)))->all();
                    if(empty($item))
                    {
                        Yii::$app->db->createCommand()->insert('checkin_record_vo', [
                            'checkin_time' => trim($v->checkin_time),
                            'image_list' => \GuzzleHttp\json_encode($v->image_list),
                            'detail_place' => isset($v->detail_place)?$v->detail_place:"",
                            'remark' => isset($v->remark)?$v->remark:"",
                            'userid' => trim($v->userid),
                            'place' => isset($v->place)?$v->place:"",
                            'longitude' => isset($v->longitude)?$v->longitude:"",
                            'visit_user' => isset($v->visit_user)?$v->visit_user:"",
                            'latitude' => isset($v->latitude)?$v->latitude:"",
                        ])->execute();
                    }
                }
            }

            if(isset($res->result->result->next_cursor))
            {
                 $this->dogetrecordlist($useridlist,$res->result->result->next_cursor,$starttime,$endtime);
            }
        }
    }

    /**
     *获得审批实例记录
     */
    public function getspslist()
    {
        $userlist=UserList::find()->select("userid")->all();
        $str=array();
        foreach ($userlist as $k=>$v)
        {
            $str[$k]=$v["userid"];
        }
        $useridlist=implode(",",$str);
        if(!empty($useridlist))
        {
            $starttime=(time()-60*60*24*2)*1000;
            $endtime=time()*1000;
            $process_code=yii::$app->params["process_code"];
            if(!empty($process_code)&&is_array($process_code))
            {
                foreach ($process_code as $vo)
                {
                    $res=$this->getSplist(trim($vo),"{$starttime}","{$endtime}","10","0",$useridlist,$this->getAccess_token());
                    if(isset($res->result->success)&&$res->result->success)
                    {
                        if(isset($res->result->result->list->process_instance_top_vo))
                        {
                            $vv=$res->result->result->list->process_instance_top_vo;
                            foreach ($vv as $k=>$v)
                            {
                                $item=ProcessInstanceTopVo::find()->where(array("process_instance_id"=>trim($v->process_instance_id),"create_time"=>trim($v->create_time),"business_id"=>trim($v->business_id)))->all();
                                if(empty($item))
                                {
                                    Yii::$app->db->createCommand()->insert('process_instance_top_vo', [
                                        'process_instance_id' => trim($v->process_instance_id),
                                        'title' => isset($v->title)?$v->title:"",
                                        'create_time' => isset($v->create_time)?$v->create_time:"",
                                        'finish_time' => isset($v->finish_time)?$v->finish_time:"",
                                        'originator_userid' => isset($v->originator_userid)?$v->originator_userid:"",
                                        'originator_dept_id' => isset($v->originator_dept_id)?$v->originator_dept_id:"",
                                        'status' => isset($v->status)?$v->status:"",
                                        'approver_userid_list' =>isset($v->approver_userid_list)?\GuzzleHttp\json_encode($v->approver_userid_list):"",
                                        'cc_userid_list' =>isset($v->cc_userid_list)?\GuzzleHttp\json_encode($v->cc_userid_list):"",
                                        'form_component_values' =>isset($v->form_component_values)?\GuzzleHttp\json_encode($v->form_component_values):"",
                                        'process_instance_result' => isset($v->process_instance_result)?$v->process_instance_result:"",
                                        'business_id' => isset($v->business_id)?trim($v->business_id):"",
                                    ])->execute();
                                }
                            }
                        }

                        if(isset($res->result->result->next_cursor))
                        {
                            $this->dogetsplist($vo,$useridlist,$res->result->result->next_cursor,$starttime,$endtime);
                        }
                    }
                }
            }

        }
        return ProcessInstanceTopVo::find()->all();
    }

    private function dogetsplist($vo,$useridlist,$cursor,$starttime,$endtime)
    {
        $res=$this->getSplist(trim($vo),"{$starttime}","{$endtime}","10",$cursor,$useridlist,$this->getAccess_token());
        if(isset($res->result->success)&&$res->result->success)
        {
            if(isset($res->result->result->list->process_instance_top_vo))
            {
                $vv=$res->result->result->list->process_instance_top_vo;
                foreach ($vv as $k=>$v)
                {
                    $item=ProcessInstanceTopVo::find()->where(array("process_instance_id"=>trim($v->process_instance_id),"create_time"=>trim($v->create_time),"business_id"=>trim($v->business_id)))->all();
                    if(empty($item))
                    {
                        Yii::$app->db->createCommand()->insert('process_instance_top_vo', [
                            'process_instance_id' => trim($v->process_instance_id),
                            'title' => isset($v->title)?$v->title:"",
                            'create_time' => isset($v->create_time)?$v->create_time:"",
                            'finish_time' => isset($v->finish_time)?$v->finish_time:"",
                            'originator_userid' => isset($v->originator_userid)?$v->originator_userid:"",
                            'originator_dept_id' => isset($v->originator_dept_id)?$v->originator_dept_id:"",
                            'status' => isset($v->status)?$v->status:"",
                            'approver_userid_list' =>isset($v->approver_userid_list)?\GuzzleHttp\json_encode($v->approver_userid_list):"",
                            'cc_userid_list' =>isset($v->cc_userid_list)?\GuzzleHttp\json_encode($v->cc_userid_list):"",
                            'form_component_values' =>isset($v->form_component_values)?\GuzzleHttp\json_encode($v->form_component_values):"",
                            'process_instance_result' => isset($v->process_instance_result)?$v->process_instance_result:"",
                            'business_id' => isset($v->business_id)?trim($v->business_id):"",
                        ])->execute();
                    }
                }
            }

            if(isset($res->result->result->next_cursor))
            {
                $this->dogetsplist($vo,$useridlist,$res->result->result->next_cursor,$starttime,$endtime);
            }
        }
    }




}